package com.axend.aerosense.room.ui.activity;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.common.adapter.ProviderMultiAdapter;
import com.axend.aerosense.room.ui.fragment.RoomSettingFragment;
import com.axend.aerosense.room.viewmodel.RoomDetailsViewModel;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gyf.immersionbar.ImmersionBar;
import com.axend.aerosense.base.activity.MvvmBaseActivity;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.base.viewmodel.BaseViewModelFactroy;
import com.axend.aerosense.common.bean.AlarmBean;
import com.axend.aerosense.common.bean.RadarBean;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.room.R;
import com.axend.aerosense.room.databinding.RoomActivityDetailsBinding;
import com.axend.aerosense.room.entity.RoomDetailsBean;
import com.axend.aerosense.room.entity.RoomItemBean;
import com.axend.aerosense.room.ui.adapter.RoomDeviceListAdapter;

import java.util.ArrayList;


/**
 * 房间详细信息界面
 * @date :2021/1/5 11:16
 */

public class RoomDetailsActivity
        extends MvvmBaseActivity<RoomActivityDetailsBinding, RoomDetailsViewModel>
        implements ILoadDataResult<RoomDetailsBean> {
    private RoomItemBean room ;
    private boolean isImmersionBarTransparent = true;
    private RoomDeviceListAdapter deviceListAdapter;
    private ProviderMultiAdapter multiAdapter;
    public ArrayList<RadarBean> radarInfo = new ArrayList<RadarBean>();
    public ArrayList<AlarmBean> logInfo = new ArrayList<AlarmBean>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        room = (RoomItemBean) getIntent().getSerializableExtra(RoomSettingFragment.OPEN_PARAM_ROOMINFO);
        setSupportActionBar(viewDataBinding.roomToolbar);
        //状态栏颜色
        setImmersionBar();
        init();
        viewModel.setRoomId(room.getRoomUuid());
        setLoadSir(viewDataBinding.roomNestedScrollView);
        showLoading();
        viewModel.onLoad();

    }

    private void init(){

        LiveDatabus.getInstance().with(Gobal.EVENT_KEY.REFESH_ROOM_DETAIL ,Integer.class)
                .observe(this, bean-> {
                    // 信息变更时重新刷新
                    viewModel.onLoad();
                });

        viewDataBinding.roomIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        viewDataBinding.roomTvRoomName.setText(room.getRoomName());
        viewDataBinding.roomTvRoomName.setFocusable(true);
        String loaction = room.getTimeZone();
        if(TextUtils.isEmpty(loaction)){
            loaction = getString(R.string.common_unset_location);
        }
        viewDataBinding.roomTvLocation.setText(loaction);
        viewDataBinding.roomDeviceList.setLayoutManager(new GridLayoutManager(this,2));
        deviceListAdapter = new RoomDeviceListAdapter(room.getRoomName());
        deviceListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                RadarBean item = deviceListAdapter.getData().get(position);
                ARouter.getInstance()
                        .build(RouterActivityPath.Dev.PAGE_DEV_HOME)
                        .withSerializable("radarBean", item)
                        .navigation();
            }
        });
        viewDataBinding.roomDeviceList.setAdapter(deviceListAdapter);
        multiAdapter = new ProviderMultiAdapter();
        viewDataBinding.roomWarningHistroyRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        viewDataBinding.roomWarningHistroyRecyclerview.setAdapter(multiAdapter);
        multiAdapter.setOnItemClickListener((adapter, view, position) -> {
            AlarmBean alarmBean = (AlarmBean) adapter.getData().get(position);
            ARouter.getInstance().build(RouterActivityPath.Home.PAGE_HOME_LOG_DETAIL).withSerializable(Gobal.IntentParamType.WARN_OBJECT, alarmBean).navigation();
        });
        viewDataBinding.roomNestedScrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                Rect headRcet = new Rect();
                viewDataBinding.roomClHead.getGlobalVisibleRect(headRcet);

                Rect toolbarRect = new Rect();
                viewDataBinding.roomToolbar.getGlobalVisibleRect(toolbarRect);

                if (headRcet.bottom > toolbarRect.top){
                    //可见
                    viewDataBinding.roomToolbar.setBackgroundResource(R.color.app_colorAccent);
                    viewDataBinding.roomIvBack.setImageResource(R.drawable.room_ic_back1);
                    viewDataBinding.roomTvRoomName.setTextColor(getResources().getColor(R.color.white));
                    viewDataBinding.roomIvAdd.setImageResource(R.drawable.common_user_icon_add);
                    viewDataBinding.roomIvSetting.setImageResource(R.drawable.room_icon_setting);
                    isImmersionBarTransparent = true;
                }else {
                    //不可见
                    viewDataBinding.roomToolbar.setBackgroundResource(R.color.white);
                    viewDataBinding.roomIvBack.setImageResource(R.drawable.room_ic_back2);
                    viewDataBinding.roomTvRoomName.setTextColor(getResources().getColor(R.color.common_text_color_black));
                    viewDataBinding.roomIvAdd.setImageResource(R.drawable.common_user_icon_add2);
                    viewDataBinding.roomIvSetting.setImageResource(R.drawable.room_icon_setting2);
                    isImmersionBarTransparent = false;
                }
                setImmersionBar();
            }
        });

        viewDataBinding.roomIvSetting.setOnClickListener(V->{
            Intent intent = new Intent(this, RoomAddActivity.class);
            intent.putExtra(RoomSettingFragment.OPEN_PARAM_ROOMINFO, room);
            startActivityForResult(intent, RoomAddActivity.RUQUST_CODE);
        });

        viewDataBinding.roomIvAdd.setOnClickListener(v -> {
            ARouter.getInstance()
                    .build(RouterActivityPath.Dev.PAGE_DEV_HOME)
                    .navigation();
        });

        viewDataBinding.roomWarningMore.setOnClickListener(v->{
            ARouter.getInstance().build(RouterActivityPath.Home.PAGE_HOME_WARNING)
                    .withString("roomUuid", room.getRoomUuid())
                    .withInt("openType", 0)
                    .navigation();
        });

        viewDataBinding.roomDevAddView.setOnClickListener(v -> ARouter.getInstance()
                .build(RouterActivityPath.Dev.PAGE_DEV_HOME)
                .navigation());

        viewDataBinding.roomRefreshLayout.setOnRefreshListener(refreshLayout->{
            viewModel.onLoad();
        });
        viewDataBinding.roomRefreshLayout.setEnableLoadMore(false);

        deviceListAdapter.setList(radarInfo);
        multiAdapter.setList(logInfo);
    }

    public void setImmersionBar() {
        if(isImmersionBarTransparent) {
            ImmersionBar.with(this)
                    .statusBarColor(R.color.app_colorAccent)
                    .fitsSystemWindows(true)
                    .statusBarDarkFont(true)
                    .autoDarkModeEnable(true).init();

        }else{
            ImmersionBar.with(this)
                    .statusBarColor(R.color.white)
                    .fitsSystemWindows(true)
                    .statusBarDarkFont(true)
                    .autoDarkModeEnable(true).init();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(null != this.getCurrentFocus()){
            /**
             * 点击空白位置 隐藏软键盘
             */
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    @Override
    public int getLayoutId() {
        return R.layout.room_activity_details;
    }

    @Override
    protected RoomDetailsViewModel getViewModel() {
        BaseViewModelFactroy<RoomDetailsBean> myViewModelFactroy = new BaseViewModelFactroy<>(this, this);
        RoomDetailsViewModel tmp = new ViewModelProvider(this, myViewModelFactroy).get(RoomDetailsViewModel.class);
        return tmp;
    }

    @Override
    public int getBindingVariable() {
        return 0;
    }


    @Override
    protected void onRetryBtnClick() {
        showLoading();
        viewModel.onLoad();
    }

    @Override
    public void loadDataSuccess(RoomDetailsBean roomDetailBean) {
        viewDataBinding.roomRefreshLayout.finishRefresh();

        radarInfo.clear();
        radarInfo.addAll(roomDetailBean.radarInfo);
        deviceListAdapter.setList(radarInfo);

        logInfo.clear();
        logInfo.addAll(roomDetailBean.logInfo);
        multiAdapter.setList(logInfo);


        if(null != room && null != roomDetailBean.roomInfo){
            if(!TextUtils.isEmpty(roomDetailBean.roomInfo.getRoomUuid())){
                room = roomDetailBean.roomInfo;
            }
        }

        String loaction = room.getTimeZone();
        if(TextUtils.isEmpty(loaction)){
            loaction = getString(R.string.common_unset_location);
        }
        viewDataBinding.roomTvLocation.setText(loaction);
        viewDataBinding.roomTvRoomName.setText(room.getRoomName());
        if(null != roomDetailBean && null != roomDetailBean.logInfo && roomDetailBean.logInfo.size()>0){
            for(AlarmBean bean :roomDetailBean.logInfo){
                bean.setRoomName(room.getRoomName());
            }
        }

        if(null == roomDetailBean.radarInfo || roomDetailBean.radarInfo.size() == 0){
            viewDataBinding.roomDevAddView.setVisibility(View.VISIBLE);
        }else{
            viewDataBinding.roomDevAddView.setVisibility(View.GONE);
        }
        viewDataBinding.setData(roomDetailBean);
        viewDataBinding.executePendingBindings();
    }

    @Override
    public void loadDataFail(String decs) {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == RoomAddActivity.RUQUST_CODE && resultCode == RoomAddActivity.RESPONSE_CODE_CLOSE){
            finish();
        }
    }
}
